import { formatTime } from '../../utils/util'
const app = getApp();
var imgListUrl = []
var promise = {}
Page({
  data: {
    index: null,
    labs:[],
    multiIndex: [0, 0, 0],
    time: '12:01',
    date: '2021-5-1',
   
    modalName: null,
    textareaAValue: '',
    textareaBValue: '',
    isteacher: false,

    repairDetails: {
      committer: '' ,   // 提交者
      title: '',        // 标题
      submitTime: '',   // 提交时间
      desc:  '',        // 描述
      state: '未处理',        // 状态
      category: '',   // 类别
      avatar: ''
    },
    imgList: [],
    imgListUrl: []
  },
  onLoad(options){
    this.setData({
      'repairDetails.category': options.category
    })
    this.judgeRole()
    this.initData()
  },

  initData(){
    let userInfo = wx.getStorageSync('userInfo')
    // console.log(userInfo)
    this.setData({
      userInfo: userInfo
    })

    let date = new Date()

    let submitTime = formatTime(date)
    this.setData({
      'repairDetails.committer' : userInfo.userName,
      'repairDetails.submitTime' : submitTime,
      'repairDetails.avatar' : userInfo.avatar,
    })
  },

  // 获取标题
  getTitle(e){
    this.setData({
      'repairDetails.title' : e.detail.value
    })
  },
  getDesc(e){
    // console.log(e)
    this.setData({
      'repairDetails.desc' : e.detail.value
    })
  },
 
  ChooseImage() {
    wx.chooseImage({
      count: 3, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册或拍照选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除这个照片吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  textareaAInput(e) {
    this.setData({
      textareaAValue: e.detail.value
    })
  },
  textareaBInput(e) {
    this.setData({
      textareaBValue: e.detail.value
    })
  },

  // 跳转到报修列表
  toRepairList(){
    wx.navigateTo({
      url: '/pages/labs/repairList?category=' + this.data.repairDetails.category,
    })
  },

  // 判断角色
  judgeRole(){
    let userInfo = wx.getStorageSync('userInfo')
    if(userInfo !=""){
      let { role } = userInfo
      if(role == "教师"){
        this.setData({
          isteacher: true
        })
      }
    }
  },
 

  getUrl(){
    let promiseArr = [];
     //  1, 将图片插到 云存储
     this.data.imgList.forEach((item,idx) => {
      let p = new Promise((resolve, reject)=>{
        wx.cloud.uploadFile({
          cloudPath: "repairImg/" + Date.now() + '.jpg',
          filePath: item
        }).then(
          res=> {
            // console.log(res.fileID)
            wx.cloud.getTempFileURL({
              fileList: [{
                fileID: res.fileID,
                maxAge: 60 * 60, // one hour
              }]
            }).then(res => {
              // get temp file URL
              // console.log(res.fileList[0].tempFileURL)
              // imgListUrl = this.data.imgListUrl
              imgListUrl.push(res.fileList[0].tempFileURL)
              // console.log(res.fileList[0].tempFileURL)
              this.setData({
                imgListUrl
              })
              resolve()
            })
          }
        )
      })
      promiseArr.push(p)
    })
    
    Promise.all(promiseArr).then(res => {
      // console.log(imgListUrl)
      this.addRepairList()
    })
  },
  



  // 提交报修
  submit(){
    
    if(this.data.repairDetails.title == "" || this.data.repairDetails.desc==""){
      wx.showToast({
        title: '内容为空',
        icon: 'error'
      })
    }else if(this.data.userInfo ==""){
      wx.showToast({
        title: '未登录',
        icon: 'error'
      })
    }else{
      wx.showLoading({
        title: '提交中',
        mask: true
      })
      this.getUrl()
    }
  },

  addRepairList(){
    wx.cloud.callFunction({
      name:'addRepairList',
      data:{
        repairDetails: this.data.repairDetails,
        imgListUrl: imgListUrl
      }
    }).then(res=>{
      // console.log(res.result._id)
      wx.cloud.callFunction({
        name:'addRepairDetails',
        data:{
          repairDetails: this.data.repairDetails,
          _id: res.result._id,
          imgListUrl: imgListUrl
        }
      }).then(res=>{
        // console.log(res)
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: '提交成功，感谢反馈',
              duration: 2000
            }).then(()=>{
              var timeout = setTimeout(()=>{
                wx.switchTab({
                  url: "/pages/labs/index",
                })
              }, 800)
            })
          },
        })
      })
    })
  },
  onUnload(){
    // clearTimeout(timeout)
  }
})